/*
 * main.c
 *
 *  Created on: Jan 27, 2013
 *      Author: justin
 */

#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include <avr/interrupt.h>

#define baud 9600
char numbers[80];
int q_in = 0;

void init_adc(int k) {
	/*initialize the ADC to free-run mode*/
	DDRC = 0x00;
	PINC = 0x00;
	ADCSRA = 0X81; //1000 0101
	ADCSRA = ADEN | ADPS2 | ADPS0;
//	SFIOR &= 0xef;
	/*non-returning function*/
}
int read_adc(int channel) {
	/*write code to pick an ADC and read it*/
	/*condition measured value
	 * (multi-sample and average it?*/
	ADMUX = 0b00100000 | channel; //set ADLAR as well as the channel being used
	char temp;
	ADCSRA |= 0xc5;		//(1<<ADSC);//0xc5;  //0xC5=1100 0101
	while (!(ADCSRA & (1 << ADSC)))
		; //busy loop while conversion finishes. ADIF marks complete
	ADCSRA ^= 0x10; //toggle ADIF to clear after conversion so  that While !(adif) works later..
	temp = 0xff & ADCH;
	return temp;
}

void serial_init() {
	/*wake and set USART mode*/
	int myubr; /*UBRR load*/
	UCSR0A = 0b00100000; /*async mode*/
	UCSR0C = 0b00000110; /*set serial format*/
	UCSR0B = ((1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0)); //0b10011000;
	myubr = (F_CPU / (16UL * (long) baud)) - 1L;
	UBRR0L = (myubr & 0xff); /*UBRR low*/
	UBRR0H = (myubr >> 8); /*UBRR high*/
	SREG = (SREG | 0x80); /*enable interrupts*/

	/*non-returning function*/
}

ISR( USART_RX_vect) {
	//q_in = q_in + 1;  /*bump index*/
	numbers[++q_in] = UDR0; /*character into queue*/
}

void uart_out(char ch) { //, FILE* stream) {
	while ((UCSR0A & (1 << UDRE0)) == 0); /*for transmitter empty*/
	UDR0 = ch;
}

int main() {
	init_adc(1);	//call to wake up analog line-in
	while (1) {
		read_adc(0);
		_delay_ms(20);		//delay to avoid flooding USART

	}
	return 1;

}
